import 'package:flutter/material.dart';
import 'package:flutter_demo/core/common/model/banner_model.dart';
import 'package:flutter_demo/core/common/model/found_ball_model.dart';
import 'package:flutter_demo/core/common/values/constants.dart' as constants;
import 'package:flutter_demo/core/common/values/gaps.dart';
import 'package:flutter_demo/core/common/values/server.dart';
import 'package:flutter_demo/ui/pages/composite/state.dart';
import 'package:flutter_demo/ui/pages/composite/widgets/banner_widget.dart';
import 'package:flutter_demo/ui/pages/composite/widgets/found_ball.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:keframe/keframe.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

import 'index.dart';
import 'widgets/play_list/found_slied_playlist.dart';

class CompositePage extends StatelessWidget {
  static const routeName = "/CompositePage";

  CompositePage({Key? key}) : super(key: key);

  final controller = Get.find<CompositeController>();
  final refreshController = RefreshController();

  // 主视图
  Widget _buildView(Component component, int index, String? nextType) {
    final itemHeight = controller.itemHeightFromType[component.showType] ?? 0;
    switch (component.showType) {
      case constants.SHOWTYPE_BANNER:
        return BannerWidget(
            key: Key(component.extInfo.hashCode.toString()),
            bannerModel: BannerModel.fromJson(component.extInfo),
            itemHeight: itemHeight);

      case constants.SHOWTYPE_BALL:
        return FoundBall(
          (component.extInfo as List).map((e) => Ball.fromJson(e)).toList(),
          itemHeight: itemHeight,
        );
      case constants.SHOWTYPE_SLIDE_LIST:
        return FoundSliedPlaylist(
          uiElementModel: component.uiElement!,
          creatives: component.creatives!,
          curIndex: index,
          itemHeight: itemHeight,
        );
      default:
        return Container(
          width: 30.w,
          height: 30.w,
          alignment: Alignment.center,
          color: Get.theme.cardColor,
          child: Text('未适配类型: ${component.showType}'),
        );
    }
  }

  //分割线
  Widget _buildDivider(String type, String? nextType) {
    switch (type) {
      case constants.SHOWTYPE_BANNER:
        return Gaps.empty;
      case constants.SHOWTYPE_BALL:
        return Gaps.line;
      default:
        return Gaps.vGap10;
    }
  }

  //具有下拉刷新功能
  Widget _buildListView(BuildContext context, PageState? state) {
    Get.log("_buildListView $state");
    if (state != null) {
      controller.expirationTime = DateTime.now().millisecondsSinceEpoch + 10;
    }
    final listScroll = ScrollController();

    listScroll.addListener(() {
      controller.ifScrolled.value = listScroll.position.pixels >= 15.0;
    });
    return SmartRefresher(
        controller: refreshController,
        enablePullUp: true,
        onRefresh: () {
          controller.getFoundRecList(refresh: true);
          //去掉刷新按钮和，下拉完成不能重用。 只可用于上拉。
          refreshController.refreshCompleted();
        },
        onLoading: () async {
          logger.d('下拉刷新-');
          refreshController.loadComplete();
        },
        child: ListView.separated(
            padding: EdgeInsets.only(bottom: 1),
            controller: listScroll,
            //index 是行号，下标
            itemBuilder: (context, index) {
              final blocks = state!.components[index];
              final nextType = index + 1 < state.components.length
                  ? state.components[index + 1].showType
                  : null;
              //页面构建时会在第一帧渲染简单的占位，在后续分别渲染其他帧，分帧渲染提高性能
              return FrameSeparateWidget(
                  index: index,
                  placeHolder: Container(
                    color: Get.theme.cardColor,
                    height: controller.itemHeightFromType[blocks.showType] ?? 0,
                  ),
                  child: _buildView(blocks, index, nextType));
            },
            separatorBuilder: (context, index) {
              final nextType = index + 1 < state!.components.length
                  ? state.components[index + 1].showType
                  : null;
              return _buildDivider(state.components[index].showType, nextType);
            },

            //页面组件数量
            itemCount: state != null ? state.components.length : 0));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      body: Stack(
        children: [
          Positioned.fill(
              top: context.mediaQueryPadding.top,
              child: GetBuilder<CompositeController>(builder: (controller) {
                if (controller.state == PageState.loding) {
                  return const Text("onLoading-----");
                } else if (controller.state == PageState.error) {
                  refreshController.refreshFailed();
                  return Gaps.empty;
                } else if (controller.state == PageState.empty) {
                  return const Text("plase init -----");
                } else {
                  refreshController.refreshCompleted();
                  return _buildListView(context, controller.state);
                }
              })),
        ],
      ),
    );
  }
}
